/**
 * proxy.js
 * @author Ulyan Sobin
 * @description Reverse proxy modules
 */

const http = require("http");
const { ErrorView } = require(".");
const { WebHttpHandler } = require("./cube-web");

class ReverseProxy extends WebHttpHandler {

	/** @type {string} */
	rootPath;

	/**
	 * 
	 * @param { string } hostname
	 * @param { number } port
	 * @param { string } rootpath
	 * @param { object } incomingCover
	 */
	constructor(hostname, port, rootpath, incomingCover) {
		super((client) => {
			const option = {
				hostname,
				port,
				path: `${this.rootPath}${client.path}`,
				method: client.request.method,
				headers: client.request.origin.headers,
			};
			if (typeof(incomingCover) == "object") {
				option.headers = Object.assign(option.headers, incomingCover);
			}
			const req = http.request(option, (res) => {
				try {
					const response = client.response.origin;
					response.writeHead(res.statusCode, res.headers);
					res.pipe(response);
				} catch (err) {
					console.err("WARNING error occured: " + err.message);
					res.end();
				}
			});
			req.on("error", (err) => {
				console.log(err.message);
				new ErrorView(500, "Internal error.").publish(client);
			});
			req.end();
		});

		if (rootpath.endsWith('/')) this.rootPath = rootpath.substr(0, rootpath.length - 1);
		else this.rootPath = rootpath;
	}
}

module.exports.ReverseProxy = ReverseProxy;